package com.tuling.jucdemo.threadpool;

import java.util.concurrent.*;

/**
 * @author :tangweiliang
 * @date : 2022/11/21 22:00
 * 未来的你会感谢现在努力的自己
 */
public class ThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService executorService1 = Executors.newCachedThreadPool();//快
        ExecutorService executorService2 = Executors.newFixedThreadPool(10);//慢
        ExecutorService executorService3 = Executors.newSingleThreadExecutor();//最慢

        RejectedExecutionHandler rejectedExecutionHandler = new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                // 写数据库的代码
            }
        };

        //自定义线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10,
                                                                      20,
                                                                      0L,
                                                                     TimeUnit.MILLISECONDS,
                                                                     new LinkedBlockingQueue<>(10),
                                                                    new MonkeyRejectedExecutionHandler());

        for (int i = 1; i <= 100; i++) {
            threadPoolExecutor.execute(new MyTask(i));
        }
    }
}

/**
 * 项目
 */
class MyTask implements Runnable {
    int i = 0;
    public MyTask(int i) {
        this.i = i;
    }
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "程序员做了第" + i + "项目");
        try {
            Thread.sleep(3000L); //执行业务逻辑
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
